<?php
/* SVN FILE: $Id: calendars_controller.php 331 2010-07-23 12:11:05Z gregory.rome $ */
/**
 * Calendars Controller.
 *
 * The calendars controller provides function to add, import, edit and compute
 * ranking.
 *
 * cBBweb : Digital Blood Bowl league interface (http://code.google.com/p/cbbweb/)
 * Copyright 2009-2010, Grégory Romé.
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2009-2010, Grégory Romé.
 * @link          http://code.google.com/p/cbbweb/ cBBweb Project
 * @package       cbbweb
 * @subpackage    cbbweb.controllers
 * @version       $Revision: 331 $
 * @modifiedby    $LastChangedBy: gregory.rome $
 * @lastmodified  $Date: 2010-07-23 12:11:05 +0000 (Fri, 23 Jul 2010) $
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */
/**
 * Calendars Controller.
 *
 * @package       cbbweb
 * @subpackage    cbbweb.controllers
 */
class CalendarsController extends AppController {
	var $name = 'Calendars';
	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function index() {
		if (!$this->championship) {
			$this->Session->setFlash(__('You must select a championship', true));
			$this->set('noview', true);
			return;
		}
		$this->set('noview', false);

		$ctype = $this->current['Championship']['idRule_Types'];
		$nbTeams = $this->current['Championship']['iNbTeams'];
		switch ($ctype) {
			case 1 /*Championship*/:
				$numGroups = $this->current['Championship']['Championship_iNbGroups'];
				$numDays = $this->currentp['Championship']['Championship_iNbMatchsPerGroup'];
				$calendars = array ();
				for ($day = $numDays; $day > 0; $day--) {
					for ($group = $numGroups; $group > 0; $group--) {
						$calendars[$day][$group] = $this->Calendar->find('all', array (
							'conditions' => array (
								'Calendar.Championship_iGroup' => $group,
								'Calendar.Championship_iDay' => $day,
								'Calendar.idRule_Listing' => $this->championship
						)
						));
					}
				}
				break;
			case 2 : /*Cup*/
				$numGroups = $this->current['Championship']['Cup_iNbGroups'];
				$numDays = $this->current['Championship']['Cup_iNbMatchsPerGroup'];
				break;
			case 3 : /*GrandChelem*/
				break;
			case 4 : /*Playoff*/
				$numGroups = $this->current['Championship']['Cup_iNbGroups'];
				$numDays = $this->current['Championship']['Cup_iNbMatchsPerGroup'];
				$calendars = array ();
				for ($day = $numDays; $day > 0; $day--) {
					$calendars[$day] = $this->Calendar->find('all', array (
						'fields' => array (
							'Calendar.idTeam_Listing_Away',
							'Calendar.idTeam_Listing_Home',
							'Calendar.Championship_iDay',
							'Calendar.Playoff_iEliminationLevel',
							'Calendar.Away_iScore',
							'Calendar.Home_iScore',
					),
						'contain' => array (
							'TeamHome' => array (
								'fields' => array ('TeamHome.strName')
					),
							'TeamAway' => array (
								'fields' => array ('TeamAway.strName')
					)
					),
						'conditions' => array (
							'Championship_iDay' => $day,
							'Calendar.idRule_Listing' => $this->championship
					),
						'order' => array ('Calendar.Championship_iGroup' => 'asc')
					));
				}
				break;
		}

		$championship['Championship'] = $this->current['Championship'];
		$this->set('championship', $championship);
		$this->set('calendars', $calendars);
		$this->set('numDays', $numDays);
		$this->set('numGroups', $numGroups);
		$this->set('nbTeams', $nbTeams);
		$this->set('ctype', $ctype);
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Calendar.', true));
			$this->redirect(array ('action' => 'index'));
		}
		$this->set('calendar', $this->Calendar->read(null, $id));
	}

	/* ------------------------------------------------------------------------ */
	/**
	 *
	 */
	function upload() {
		if (!$this->championship) {
			$this->Session->setFlash(__('You must select a championship', true));
			$this->set('noform', true);
			return;
		}
		$this->set('noform', false);

		if (!empty ($this->data['Calendar'])) {
			$file = $this->data['Calendar']['MatchReport'];
			if (!$this->isUploadedFile($file)) {
				$this->Session->setFlash(__('Upload failed', true));
			} else {
				rename($file['tmp_name'], '/tmp/last_report.sqlite');
				$this->update();
			}
		}
	}

	/**
	 *
	 * @todo description
	 */
	function update() {
		$this->Calendar->changeDataSource('sqlite');
		$this->Calendar->recursive = -1;
		$calendar = $this->Calendar->find('first');
		$this->Calendar->changeDataSource('default');

		if(!$this->__updateCalendar($calendar)) {
			return;
		}

		if(!$this->__updateTeams($calendar)) {
			return;
		}

		if(!$this->__updatePlayers()) {
			return;
		}

		$this->Session->setFlash(__('Calendar imported', true));
		$this->redirect(array ('action' => 'index'));
	}

	private function __updateCalendar($calendar) {
		$result = $this->Calendar->find('first', array (
			'fields' => array ('Calendar.ID','Calendar.bPlayed'),
			'conditions' => array (
				'idChampionship' => $this->championship,
				'Calendar.idTeam_Listing_Away' => $calendar['Calendar']['idTeam_Listing_Away'],
				'Calendar.idTeam_Listing_Home' => $calendar['Calendar']['idTeam_Listing_Home'],
				'Calendar.Championship_iSeason' => $this->current['Championship']['iSeason']
		)));

		if(!$result) {
			unset($calendar['Calendar']['ID']);
			$calendar['Calendar']['idRule_Listing'] = $this->championship;
			$calendar['Calendar']['Championship_iSeason'] = $this->current['Championship']['iSeason'];
			$calendar['Calendar']['bPlayed'] = 1;
		}else {
			if($result['Calendar']['bPlayed'] == 1) {
				$this->Session->setFlash(__('Match already played', true));
				return false;
			}

			$calendar['Calendar']['ID'] = $result['Calendar']['ID'];
			unset($calendar['Calendar']['idRule_Listing']);
			unset($calendar['Calendar']['Championship_iSeason']);
			$calendar['Calendar']['bPlayed'] = 1;
		}

		if(!$this->Calendar->save($calendar)) {
			$this->Session->setFlash(__('Unable to save Calendar', true));
			return false;
		}

		return true;
	}

	/**
	 *
	 * @todo description
	 */
	private function __updateTeams($calendar) {

		$this->__updateTeam($calendar, 'Away');
		return;
		$this->__updateTeam($calendar, 'Home');

		return true;
	}

	/**
	 *
	 * @todo description
	 */
	private function __updateTeam($calendar, $team) {

		$this->__parseCalendar($calendar['Calendar'], $team);

		$this->Calendar->TeamAway->StatisticsTeam->recursive = -1;
		$statistics = $this->Calendar->TeamAway->StatisticsTeam->find('first', array(
			'conditions' => array('StatisticsTeam.idTeam_Listing', $calendar['Calendar']['idTeam_Listing'])
		));

		if($statistics) {
			$this->debug($statistics,false);
			$this->__updateTeamStatistics(&$statistics['StatisticsTeam'], $calendar['Calendar']);
			$this->debug($statistics,false);
			return;
			$this->Calendar->TeamAway->StatisticsTeam->save($statistics);
		}

		return true;
	}

	/**
	 *
	 */
	private function __parseCalendar(&$calendar, $team) {

		if($calendar['Away_iScore'] > $calendar['Home_iScore']) {
			$calendar['Away_Win'] = 1;
			$calendar['Home_Win'] = -1;
		} else if($calendar['Away_iScore'] == $calendar['Home_iScore']) {
			$calendar['Away_Win'] = 0;
			$calendar['Home_Win'] = 0;
		} else {
			$calendar['Away_Win'] = -1;
			$calendar['Home_Win'] = 1;
		}

		foreach ($calendar as $key => $value) {
			if(ereg('_'.$team, $key)){
				unset($calendar[$key]);
				$nkey = str_replace('_'.$team, '', $key);
				$calendar[$nkey] = $value;
			}	else if(ereg($team.'_', $key)){
				unset($calendar[$key]);
				$nkey = str_replace($team.'_', '', $key);
				$calendar[$nkey] = $value;
			}
		}
	}

	/**
	 *
	 */
	private function __updateTeamStatistics(&$stats, $calendar) {
		$stats['iMatchPlayed']++;
		foreach ($calendar as $key => $value) {

			if(ereg('Home',$key) || ereg('Away',$key)) { continue; }
			if(ereg('Championship', $key)) { continue; }
			switch ( $key ) {
    		case 'iRating':
    			$stats['iBestMatchRating'] = $calendar[$key] > $stats['iBestMatchRating'] ? $calendar[$key] : $stats['iBestMatchRating'];
    			$stats['Average_iMatchRating'] = (($stats['Average_iMatchRating']*($stats['iMatchPlayed']-1))+$calendar[$key])/$stats['iMatchPlayed'];
    			break;
    		case 'iCashEarned':
    			//FIXME: MatchReport does not contain iCashEarned
    			//$stats[$key] = $stats[$key] + $calendar[$key];
    			//$stats['Average_iCashEarned'] = $stats[$key] / $stats['iMatchPlayed'];
    			break;
    		case 'iSpectators':
    			//FIXME: StatisticsTeam does not contain iSpectators
    			//$stats[$key] = $stats[$key] + $calendar[$key];
    			//$stats['Average_iSpectators'] = $stats[$key] / $stats['iMatchPlayed'];
    			break;
    		case 'iPossessionBall':
    		case 'Occupation_iOwn':
    		case 'Occupation_iTheir':
    				$stats[$key] = (($stats[$key]*($stats['iMatchPlayed']-1))+$calendar[$key])/$stats['iMatchPlayed'];
    				break;
    		case 'Win':
    			switch ($value) {
    				case 1:
    					$stats['iWins']++;
    					break;
    				case 0:
    					$stats['iDraws']++;
    					break;
    				case -1:
    					$stats['iLoss']++;
    					break;
    			}
    			break;
    		case 'bPlayed':
    		case 'idTeam_Listing':
    		case 'iScore':
    		case 'iReward':
    			//FIXME: MatchReport does not contain iReward
				case 'ID':
				case 'idTeam_Listing':
				case 'idRule_Listing':
				case 'iSeason':
				case 'bFinished':
				case 'Playoff_iEliminationLevel':
				case 'iMetersRunning':
					break;
				case 'iMetersPassing':
					$stats['Inflicted_'.$key] = $stats['Inflicted_'.$key] + $calendar[$key];
					break;
				default:
						$stats[$key] = $stats[$key] + $calendar[$key];
				break;
			}
		}


	}

	/**
	 *
	 * @todo description
	 */
	private function __updatePlayers() {

		$this->__updatePlayerStatistics($this->Calendar->TeamAway,
			'away_player_listing', 'away_statistics_players');
		$this->__updatePlayerStatistics($this->Calendar->TeamHome,
			'home_player_listing', 'home_statistics_players');

		return true;
	}

	/**
	 *
	 * @todo description
	 * @param $Team Team Model instanciation
	 * @param $players_table
	 * @param $players_stats_table
	 */
	private function __updatePlayerStatistics($Team, $players_table, $players_stats_table) {
		$Team->Player->changeDataSource('sqlite', $players_table);
		$Team->Player->StatisticsPlayer->changeDataSource('sqlite', $players_stats_table);
		$teamPlayers = $Team->Player->find('all', array(
			'contain' => array('StatisticsPlayer')
		));
		$Team->Player->changeDataSource('default', 'player_listing');
		$Team->Player->StatisticsPlayer->changeDataSource('default', 'statistics_players');

		foreach ($teamPlayers as $teamPlayer) {
			if (!$teamPlayer['Player']['bGenerated']) {
				$player = $Team->Player->find('first', array (
					'conditions' => array ('Player.ID' => $teamPlayer['Player']['ID'])
				));

				$Team->Player->StatisticsPlayer->recursive = -1;
				$statisticsPlayer = $Team->Player->StatisticsPlayer->find('first', array(
					'conditions' => array('StatisticsPlayer.idPlayer_Listing' => $teamPlayer['Player']['ID'])
				));

				if($statisticsPlayer) {
					$this->__updatePlayerStats(&$statisticsPlayer['StatisticsPlayer'],
						$teamPlayer['StatisticsPlayer']);
					$Team->Player->StatisticsPlayer->save($statisticsPlayer);
				}

				$Team->Player->StatisticsSeasonPlayer->recursive = -1;
				$statisticsSeasonPlayer = $Team->Player->StatisticsSeasonPlayer->find('first', array(
					'conditions' => array(
						'StatisticsSeasonPlayer.idPlayer_Listing' => $teamPlayer['Player']['ID'],
						'StatisticsSeasonPlayer.idRule_Listing' => $this->championship,
						'StatisticsSeasonPlayer.iSeason' => $this->current['Championship']['iSeason']
					)
				));

				if($statisticsSeasonPlayer) {
					$this->__updatePlayerStats(&$statisticsSeasonPlayer['StatisticsSeasonPlayer'],
						$teamPlayer['StatisticsPlayer']);
						$Team->Player->StatisticsSeasonPlayer->save($statisticsSeasonPlayer);
				}
			}
		}
	}

	/**
	 *
	 */
	private function __updatePlayerStats(&$stats, $new) {
		foreach ($new as $key => $value) {
				switch ( $key ) {
				case 'ID':
				case 'idPlayer_Listing':
				case 'idRule_Listing':
				case 'iSeason':
				case 'bFinished':
					break;
				default:
						$stats[$key] = $stats[$key] + $new[$key];
					break;
			}
		}
	}
}
?>
